import { dialog, toast } from '@/composables/util'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { logout, updatepassword } from '@/api/manager'
import { ref, reactive } from 'vue'

// 修改密码
export function useResetPassword () {
  const router = useRouter()
  const store = useStore()
  // 修改密码
  const FormDrawerREF = ref(null) //通过绑定ref来获取子组件
  const resetPassword = () => {
    FormDrawerREF.value.open()
  }
  const formRef = ref(null)
  // const drawer = ref(false)
  const form = reactive({
    oldpassword: '',
    password: '',
    repassword: ''
  })
  // 表单验证
  // const loading = ref(false) // 按钮加载已封装到FormDrawer.vue
  const passwordRules = [
    {
      required: true,
      message: '请输入新密码',
      trigger: 'blur'
    }
  ]
  const rules = {
    oldpassword: [
      {
        required: true,
        message: '请输入旧密码',
        trigger: 'blur'
      }
    ],
    password: passwordRules,
    repassword: passwordRules
  }
  // 表单提交
  const onSubmit = () => {
    formRef.value.validate(valid => {
      if (!valid) {
        toast('修改失败', '请按要求填写', 'error')
      } else {
        // loading.value = true // 按钮加载已封装到FormDrawer.vue
        FormDrawerREF.value.showLoading()
        updatepassword(form)
          .then(res => {
            toast('修改成功', '修改成功，请重新登录！', 'success')
            // 删除token
            store.dispatch('USER_LOGOUT')
            // 跳转回登录页面
            router.push('/login')
          })
          .finally(() => {
            // loading.value = false  // 按钮加载已封装到FormDrawer.vue
            FormDrawerREF.value.hideLoading()
          })
      }
    })
  }
  return { resetPassword, FormDrawerREF, formRef, form, rules, onSubmit }
}

// 退出登录
export const useLogout = () => {
  const router = useRouter()
  const store = useStore()
  // 退出登录
  const handleLogout = () => {
    dialog('是否退出登录?', '提示', 'warning').then(() => {
      // 调用退出登录接口
      // logout().finally(() => {
      store.dispatch('USER_LOGOUT')
      // 跳转回登录页
      router.push('/login')
      // 提示退出登录
      toast('退出登录', '退出登录成功', 'success')
      // })
    })
  }
  return { handleLogout }
}
